#!/bin/bash
#
# clandestine.googlecode.com
#

# error function
function Error () {
	echo -e "$1" > /dev/stderr
	exit 1
}
# some sanity checks and constants to use
[[ $# > 0 ]] || Error "Syntax: `basename $0` <iface>\nThis script is normally called from ifupdown subsystem."
(( $UID )) && Error "Superuser privileges required."
if IWLIST=`which iwlist`; then
	readonly IWLIST
else
	Error "Can't find iwlist. Perhaps you should install wireless-tools."
fi
readonly IFACE="$1"
readonly INTERFACES="/etc/network/interfaces"
# do the scan
readonly -a SSIDS=( `$IWLIST "$IFACE" scan | awk -F ":" -- '/ESSID:/ { gsub (/ /, "_", $2); print (substr ($2, 2, length ($2) - 2)) }'` )
(( ${#SSIDS[@]} )) || Error "No wireless networks found."
# now collect profiles from interfaces
readonly -a PROFILES=( `sed --quiet "s|^\\s*iface\\s*$IFACE-\\([^[:space:]]*\\).*|\\1|p" "$INTERFACES"` )
(( ${#PROFILES[@]} )) || Error "No profiles defined in $INTERFACES, can't continue."
# compare ssids with profiles and choose the network
RESULT="$PROFILES" # the first defined profile is a default one
for PROFILE in "${PROFILES[@]:1}"; do
	for SSID in "${SSIDS[@]}"; do
		if [[ "$SSID" == "$PROFILE" ]]; then
			RESULT="$PROFILE";
			break 2
		fi
	done
done
# return the result
echo "$IFACE-$RESULT"
